<template>
  <el-dialog
    top="30px"
    width="800px"
    title="项目受理"
    append-to-body
    :close-on-click-modal="false"
    :before-close="beforeClose"
    :visible.sync="visible"
  >
    <table class="table table-sm table-borderless">
      <tbody>
        <tr>
          <td width="16%" class="text-muted">项目名称：</td>
          <td width="34%">{{ relatedData.customer_name || relatedData.customer_name }}</td>
          <td width="16%" class="text-muted">项目地址：</td>
          <td width="34%">{{ relatedData.address }}</td>
        </tr>
        <tr>
          <td class="text-muted">负责人：</td>
          <td>{{ relatedData.corp_name }}</td>
          <td class="text-muted">联系电话：</td>
          <td>{{ relatedData.mobile_no }}</td>
        </tr>
        <tr>
          <td class="text-muted">申请金额：</td>
          <td>{{ relatedData.apply_funds || '-' }} 万元</td>
          <td class="text-muted">申请年限：</td>
          <td>{{ relatedData.load_years || '-' }} 年</td>
        </tr>
        <tr>
          <td class="text-muted">推荐机构：</td>
          <td>{{ relatedData.submit_person_name || '-' }}</td>
          <td class="text-muted">推荐时间：</td>
          <td>{{ $utils.dateFormat(relatedData.recommend_time, 'yyyy.MM.dd') || '-' }}</td>
        </tr>
        <tr>
          <td class="text-muted">贷款用途：</td>
          <td colspan="3">{{ relatedData.funds_use_dir || '-' }}</td>
        </tr>
        <tr v-if="relatedData.bank_id">
          <td class="text-muted">贷款银行：</td>
          <td colspan="3">{{ relatedData.bank_name }}</td>
        </tr>
        <tr>
          <td>
            <div class="pt-3">
              <span class="text-danger" v-if="!viewModel">*</span>
              <span class="text-muted">项目类型：</span>
            </div>
          </td>
          <td colspan="3">
            <div class="pt-3" v-if="viewModel">{{ enumGuatypeStatus[relatedData.gua_type] }}</div>
            <div class="pt-3" v-else>
              <span v-if="!isUserTown">直担业务</span>
              <select-gua-type
                v-else
                placeholder="请选择项目类型"
                v-model="putData.gua_type"
                @change="handleGuaTypeChange"
                class="form-control-ml"
              ></select-gua-type>
              <div class="text-danger text-validator" v-if="!viewModel">
                <small v-if="validatorData.gua_type">请选择项目类型</small>
              </div>
            </div>
          </td>
        </tr>
        <tr v-show="needAccessAgency">
          <td>
            <span class="text-danger" v-if="!viewModel">*</span>
            <span class="text-muted">联保机构：</span>
          </td>
          <td colspan="3">
            <span v-if="viewModel">{{ relatedData.recommend_service_name }}</span>
            <select-org-credit
              v-else
              v-model="putData.recommend_service"
              @change="handleAccessAgencyChange"
              :gua-type="putData.gua_type"
              class="form-control-ml"
              placeholder="请选择联保机构"
            ></select-org-credit>
            <div class="text-danger text-validator" v-if="!viewModel">
              <small v-if="!accessAgencyValid">请选择联保机构</small>
            </div>
          </td>
        </tr>
        <tr>
          <td>
            <span class="text-danger" v-if="!viewModel">*</span>
            <span class="text-muted">负责人A角：</span>
          </td>
          <td colspan="3">
            <span v-if="viewModel">{{ relatedData.res_a_name }}</span>
            <select-staff
              v-else
              v-model="putData.res_a"
              @change="setValidator('res_a')"
              class="form-control-ml"
              placeholder="请选择项目负责人: A角"
            ></select-staff>
            <div class="text-danger text-validator" v-if="!viewModel">
              <small v-if="validatorData.res_a">请选择项目负责人: A角</small>
            </div>
          </td>
        </tr>
        <tr>
          <td>
            <span class="text-danger" v-if="!viewModel">*</span>
            <span class="text-muted">负责人B角：</span>
          </td>
          <td colspan="3">
            <span v-if="viewModel">{{ relatedData.res_b_name }}</span>
            <select-staff
              v-else
              v-model="putData.res_b"
              @change="setValidator('res_b')"
              class="form-control-ml"
              placeholder="请选择项目负责人: B角"
            ></select-staff>
            <div class="text-danger text-validator">
              <small v-if="validatorData.res_b">请选择项目负责人: B角</small>
            </div>
          </td>
        </tr>
        <template v-if="!relatedData.bank_id && !viewModel">
          <tr>
            <td class="text-muted">是否指定银行：</td>
            <td colspan="3">
              <div class="mb-2">
                <el-switch
                  v-model="isBank"
                  @change="setBank"
                  active-color="#67C23A"
                  inactive-color="#F56C6C"
                  active-value="1"
                  :active-text="+isBank === 1 ? '是' : '否'"
                  inactive-value="0"
                ></el-switch>
              </div>
            </td>
          </tr>
          <tr v-if="+isBank === 1">
            <td></td>
            <td colspan="3">
              <select-org-bank
                v-if="![2, 4].includes(+putData.gua_type)"
                :project-type="putData.gua_type"
                v-model="putData.public_bank_ids"
                placeholder="请选择银行名称"
                @select="setPublic"
                class="form-control-ml"
                :filterable="true"
              ></select-org-bank>

              <select-org-bank
                v-else
                v-model="putData.bank_id"
                placeholder="选择指定银行（非必填）"
                @select="setBankName"
                filterable
                clearable
                class="form-control-ml"
              ></select-org-bank>
            </td>
          </tr>
        </template>
      </tbody>
    </table>
    <!-- <div v-if="viewModel">
      指定银行： {{relatedData.public_bank_names}}
    </div> -->
    <div class="text-center mt-5" v-if="!viewModel">
      <el-button @click="submit" type="primary" :loading="submitLoading" class="btn-long">
        确认受理
      </el-button>
      <el-button @click="beforeClose" class="btn-long">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { enumGuatype as enumGuatypeStatus } from '@/credit/plugins/enumTown'

import SelectStaff from '@/components/select/SelectStaff'
import SelectOrgBank from '@/credit/components/select/SelectOrgBank'
import SelectOrgCredit from '@/credit/components/select/SelectOrgCredit'
import SelectGuaType from '@/credit/components/select/SelectGuaType'

export default {
  components: {
    SelectStaff,
    SelectOrgBank,
    SelectGuaType,
    SelectOrgCredit,
  },
  props: {
    viewModel: Boolean,
    visible: Boolean,
    relatedData: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  data() {
    return {
      enumGuatypeStatus,
      isBank: '0',
      putData: {
        is_approval: '',
        res_a: '',
        res_b: '',
        public_bank_ids: '',
        pre_approval_person: '',
        approved_date: '',
        gua_type: '',
        recommend_service: '',
        recommend_service_name: '',
      },
      submitLoading: false,
      validatorData: {
        gua_type: false,
        res_a: false,
        res_b: false,
      },
    }
  },
  computed: {
    ...mapGetters(['userId', 'user', 'clientId']),
    isUserTown() {
      return [3, 2].includes(this.user.orgRegionLever)
    },

    // 是否需要选择联保机构
    needAccessAgency() {
      return this.putData.gua_type && +this.putData.gua_type !== 2
    },

    // 联保机构是否验证通过
    accessAgencyValid() {
      return !this.needAccessAgency || !!this.putData.recommend_service
    },
  },
  watch: {
    relatedData: {
      handler: function () {
        if (this.relatedData.public_bank_ids) {
          this.isBank = '1'
        } else {
          this.isBank = '0'
        }
        Object.keys(this.putData).forEach(key => {
          this.putData[key] = this.relatedData[key] || ''
        })
        if (!+this.putData.gua_type) {
          this.putData.gua_type = ''
        }
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {},
  created() {},
  methods: {
    setValidator(key) {
      const status = !!this.putData[key]
      this.validatorData[key] = !status
    },
    handleGuaTypeChange() {
      this.validatorData.gua_type = !this.putData.gua_type
    },
    handleAccessAgencyChange(val, agency) {
      this.putData.recommend_service_name = agency.service_agency_name || ''
    },
    beforeClose() {
      this.validatorData = {
        gua_type: false,
        res_a: false,
        res_b: false,
      }
      this.$emit('update:visible', false)
    },
    setBank() {
      this.putData.public_bank_ids = ''
      this.putData.public_bank_names = ''
    },
    setPublic(bank) {
      this.putData.public_bank_names = bank.agency_name
    },
    setBankName(bank) {
      this.putData.bank_name = bank.agency_name
    },
    submit() {
      this.putData.gua_type = this.isUserTown ? this.putData.gua_type : 2
      Object.keys(this.validatorData).forEach(key => {
        this.setValidator(key)
      })
      if (!this.putData.gua_type) {
        return this.$message.warning('请选择项目类型')
      }
      if (!this.accessAgencyValid) {
        return this.$message.warning('请选择联保机构')
      }
      if (!this.putData.res_a) {
        return this.$message.warning('请选择项目负责人A角')
      }
      if (!this.putData.res_b) {
        return this.$message.warning('请选择项目负责人B角')
      }
      if (+this.isBank === 1) {
        if (!this.putData.public_bank_ids && ![2, 4].includes(+this.putData.gua_type)) {
          return this.$message.warning('请选择项目指定银行')
        }
        if (!this.putData.bank_id && [2, 4].includes(+this.putData.gua_type)) {
          return this.$message.warning('请选择项目指定银行')
        }
      } else {
        this.putData.public_bank_ids = null
      }

      const {
        recommend_service: serviceId,
        recommend_service_name: serviceName,
        ...data
      } = this.putData
      if (this.needAccessAgency) {
        data.recommend_service = serviceId
        data.recommend_service_name = serviceName
      }

      data.is_approval = 1
      data.service_id = this.clientId
      data.pre_approval_person = this.userId
      data.approved_date = this.$utils.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss')
      this.submitLoading = true
      this.$api
        .updateData(
          this.$serviceName,
          'customer_related',
          this.relatedData.customer_related_id,
          data
        )
        .then(() => {
          this.$emit('success', true)
          this.$message.success('项目受理成功')
          this.beforeClose()
        })
        .catch(() => {
          this.$message.error('项目受理失败')
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
  },
}
</script>
<style lang="scss" scoped>
.select-item {
  margin-left: 125px;
}
.text-decoration {
  font-size: 1.2rem;
  text-decoration: underline;
}
.text-validator {
  height: 15px;
  line-height: 1;
}
.form-label {
  vertical-align: top;
}
</style>
